package org.yohailong.studyreactfrombilibili.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author 朱海龙
 * 2025/9/8 22:14
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyObjectHandler();
    }


    public static final class MyObjectHandler implements MetaObjectHandler {

        private static final String CREATE_TIME = "createTime";
        private static final String UPDATE_TIME = "updateTime";

        @Override
        public void insertFill(MetaObject metaObject) {
            boolean hasCreateTime = metaObject.hasGetter(CREATE_TIME);
            if (hasCreateTime) {
                this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
            }
            boolean hasUpdateTime = metaObject.hasGetter(UPDATE_TIME);
            if (hasUpdateTime) {
                this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
            }
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            boolean hasUpdateTime = metaObject.hasGetter(UPDATE_TIME);
            if (hasUpdateTime) {
                this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
            }
        }
    }

}
